import { LocalStorage, Platform } from 'quasar'
import { Plugins } from '@capacitor/core'
const { Storage } = Plugins

export const nlocalstorage = {
  set (key, value, expired) {
    /*
        * set 存储方法
        * @ param {String}     key 键
        * @ param {String}     value 值，
        * @ param {String}     expired 过期时间，以分钟为单位，非必须
        * @ 由@IT·平头哥联盟-首席填坑官∙苏南 分享,交流：912594095
        */
    this.remove(key)
    appStorageSet(key, JSON.stringify(value))
    if (expired) {
      appStorageSet(key + '__expires__', Date.now() + 1000 * 60 * expired)
    }
    return value
  },
  get (key, event) {
    appStorageGet(key + '__expires__').then(expired => {
      const now = Date.now()
      expired = expired || Date.now + 1
      if (now >= expired) {
        this.remove(key)
      }
      appStorageGet(key).then(value => {
        if (value) {
          value = JSON.parse(value)
        }
        event(value)
      })
    })
  },
  remove (key) {
    appStorageRemove(key)
    appStorageRemove(key + '__expires__')
  }
}
const appStorageSet = function (key, value) {
  if (Platform.is.capacitor) {
    Storage.set({
      key: key,
      value: value
    })
  } else {
    LocalStorage.set(key, value)
  }
}

const appStorageGet = async function (key) {
  if (Platform.is.capacitor) {
    const { value } = await Storage.get({ key: key })
    return value
  } else {
    const value = LocalStorage.getItem(key)
    return value
  }
}

const appStorageRemove = function (key) {
  if (Platform.is.capacitor) {
    return Storage.remove({ key: key })
  } else {
    return LocalStorage.remove(key)
  }
}
